package com.xky.ui.module.productManagement.add;

import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class AddProduct extends JFrame {
    private JPanel jPanel1, jPanel2, jPanel3;
    private JTextField[] textFields;
    private JComboBox<String> unitComboBox;
    private JComboBox<String> isActiveComboBox;
    
    // 预定义的有效计量单位列表
    private static final Set<String> VALID_UNITS = new HashSet<>(Arrays.asList(
            "个", "箱", "袋", "瓶", "千克", "克", "吨", "升", "毫升", "米", "厘米", "套",
            "件", "双", "台", "包", "盒", "桶", "卷", "张", "只", "块", "片", "支"
    ));
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    
    public AddProduct() {
        setTitle("添加商品");
        setSize(500, 650);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        init();
        setVisible(true);
    }

    void init() {
        setLayout(new BorderLayout()); // 设置主布局
        
        // 创建主面板并设置背景渐变
        JPanel mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 标题面板
        jPanel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
        jPanel2.setOpaque(false);
        
        JLabel jLabel = new JLabel("添加商品信息");
        jLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        jLabel.setForeground(PRIMARY_COLOR);
        jPanel2.add(jLabel);
        
        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(PRIMARY_COLOR);
        separator.setPreferredSize(new Dimension(450, 2));
        
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);
        titlePanel.add(jPanel2, BorderLayout.CENTER);
        titlePanel.add(separator, BorderLayout.SOUTH);
        titlePanel.setBorder(new EmptyBorder(0, 0, 20, 0));
        
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 表单面板
        jPanel1 = new JPanel(new GridBagLayout());
        jPanel1.setOpaque(false);
        
        JLabel[] labels = new JLabel[]{
                new JLabel("商品编码 *"),
                new JLabel("商品名称 *"),
                new JLabel("所属分类ID *"),
                new JLabel("计量单位 *"),
                new JLabel("库存量 *"),
                new JLabel("是否上架 *")
        };

        // 创建正确大小的文本框数组
        textFields = new JTextField[4];

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0;
        gbc.insets = new Insets(10, 10, 10, 10);

        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font inputFont = new Font("微软雅黑", Font.PLAIN, 16);
        
        // 创建圆角边框的文本框样式
        for (int i = 0; i < labels.length; i++) {
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.anchor = GridBagConstraints.WEST;
            labels[i].setFont(labelFont);
            labels[i].setForeground(PRIMARY_COLOR);
            jPanel1.add(labels[i], gbc);
            
            gbc.gridx = 1;
            gbc.weightx = 1.0;
            
            if (i < 3) {
                // 前三个是文本框：商品编码、商品名称、分类ID
                textFields[i] = new JTextField(20);
                textFields[i].setFont(inputFont);
                textFields[i].setPreferredSize(new Dimension(250, 35));
                jPanel1.add(textFields[i], gbc);
            } else if (i == 3) {
                // 计量单位下拉框
                unitComboBox = new JComboBox<>(VALID_UNITS.toArray(new String[0]));
                unitComboBox.setFont(inputFont);
                unitComboBox.setPreferredSize(new Dimension(250, 35));
                unitComboBox.setBackground(Color.WHITE);
                jPanel1.add(unitComboBox, gbc);
            } else if (i == 4) {
                // 库存量文本框
                textFields[3] = new JTextField(20);
                textFields[3].setFont(inputFont);
                textFields[3].setPreferredSize(new Dimension(250, 35));
                jPanel1.add(textFields[3], gbc);
            } else {
                // 是否上架下拉框
                isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
                isActiveComboBox.setFont(inputFont);
                isActiveComboBox.setPreferredSize(new Dimension(250, 35));
                isActiveComboBox.setBackground(Color.WHITE);
                jPanel1.add(isActiveComboBox, gbc);
            }
        }

        // 添加表单面板到卡片容器
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());
        formCard.add(jPanel1, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        mainPanel.add(formCard, BorderLayout.CENTER);

        // 按钮面板
        jPanel3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        jPanel3.setOpaque(false);
        
        JButton submitButton = new JButton("提交");
        submitButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        submitButton.setPreferredSize(new Dimension(120, 40));
        submitButton.setBackground(BUTTON_COLOR);
        submitButton.setForeground(Color.WHITE);
        submitButton.setFocusPainted(false);
        submitButton.setBorderPainted(false);
        
        JButton resetButton = new JButton("重置");
        resetButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        resetButton.setPreferredSize(new Dimension(120, 40));
        resetButton.setBackground(Color.LIGHT_GRAY);
        resetButton.setForeground(Color.WHITE);
        resetButton.setFocusPainted(false);
        resetButton.setBorderPainted(false);
        
        jPanel3.add(submitButton);
        jPanel3.add(resetButton);
        
        mainPanel.add(jPanel3, BorderLayout.SOUTH);
        add(mainPanel);

        // 重置按钮事件
        resetButton.addActionListener(_ -> {
            for (JTextField field : textFields) {
                field.setText("");
            }
            unitComboBox.setSelectedIndex(0);
            isActiveComboBox.setSelectedIndex(0);
        });

        // 提交按钮事件
        submitButton.addActionListener(e -> {
            try {
                // 获取输入值
                String productCode = textFields[0].getText().trim();
                String productName = textFields[1].getText().trim();
                String categoryIdStr = textFields[2].getText().trim();
                String unitOfMeasure = (String) unitComboBox.getSelectedItem();
                String minStockLevelStr = textFields[3].getText().trim();
                String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1，"否"对应0
                
                // 进行输入校验
                if (!validateInputs(productCode, productName, categoryIdStr, 
                                   unitOfMeasure, minStockLevelStr, isActive)) {
                    return; // 如果校验不通过，直接返回
                }
                
                // 校验通过后，转换数据类型
                Integer categoryId = Integer.valueOf(categoryIdStr);
                Integer minStockLevel = Integer.valueOf(minStockLevelStr);

                if (addProduct(productCode, productName, categoryId, unitOfMeasure, minStockLevel, isActive)) {
                    JOptionPane.showMessageDialog(AddProduct.this, "商品信息添加成功！", "成功提示", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(AddProduct.this, "商品信息添加失败！", "失败提示", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(AddProduct.this, "发生错误：" + ex.getMessage(), "错误提示", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
    
    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setOpaque(false);
        
        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
            )
        ));
        
        return panel;
    }
    
    /**
     * 校验用户输入的数据
     * @return 如果所有输入都有效返回true，否则返回false
     */
    private boolean validateInputs(String productCode, String productName, String categoryIdStr, 
                                  String unitOfMeasure, String minStockLevelStr, String isActive) {
        // 1. 校验商品编码
        if (productCode.isEmpty()) {
            showValidationError("商品编码不能为空");
            return false;
        }
        
        // 2. 校验商品名称
        if (productName.isEmpty()) {
            showValidationError("商品名称不能为空");
            return false;
        }
        
        // 3. 校验分类ID
        if (categoryIdStr.isEmpty()) {
            showValidationError("分类ID不能为空");
            return false;
        }
        
        try {
            Integer.parseInt(categoryIdStr);
        } catch (NumberFormatException e) {
            showValidationError("分类ID必须是数字");
            return false;
        }
        
        // 4. 校验计量单位
        if (unitOfMeasure == null || unitOfMeasure.isEmpty()) {
            showValidationError("计量单位不能为空");
            return false;
        }
        
        // 5. 校验最低库存
        if (minStockLevelStr.isEmpty()) {
            showValidationError("库存量不能为空");
            return false;
        }
        
        try {
            int minStock = Integer.parseInt(minStockLevelStr);
            if (minStock < 0) {
                showValidationError("库存量不能小于0");
                return false;
            }
        } catch (NumberFormatException e) {
            showValidationError("库存量必须是数字");
            return false;
        }

        // 所有校验通过
        return true;
    }
    
    /**
     * 显示验证错误信息
     * @param message 错误信息
     */
    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
    }

    /**
     * 添加商品信息方法
     * @param productCode
     * @param productName
     * @param categoryId
     * @param unitOfMeasure
     * @param minStockLevel
     * @param isActive
     * @return
     */

    public boolean addProduct(String productCode, String productName, Integer categoryId, String unitOfMeasure, Integer minStockLevel, String isActive) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("insert into products(product_code, product_name, category_id, unit_of_measure, min_stock_level, is_active, created_time, updated_time) values (?,?,?,?,?,?,now(),now())", Statement.RETURN_GENERATED_KEYS);
            preparedStatement.setString(1, productCode);
            preparedStatement.setString(2, productName);
            preparedStatement.setInt(3, categoryId);
            preparedStatement.setString(4, unitOfMeasure);
            preparedStatement.setInt(5, minStockLevel);
            preparedStatement.setString(6, isActive);

            int i = preparedStatement.executeUpdate();
            
            if (i > 0){
                System.out.println("影响行数为" + i + "添加成功！");
                return true;
            } else {
                System.out.println("影响行数为" + i + "添加失败！");
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    public static void main(String[] args) {
        try {
            // 尝试使用系统外观
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(AddProduct::new);
    }
}